package cn.wqk.demo.controller;

import cn.wqk.demo.pojo.User;
import cn.wqk.demo.service.LoginService;
import cn.wqk.demo.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 吴青珂
 * @Date: 2020/12/25/11:24
 * @Description:
 */
@RestController
@Slf4j
@RequestMapping("login")
@CrossOrigin("*")
public class LoginController {
    @Autowired
    private LoginService loginService;
    @PostMapping("/login")
    public Map<String,Object> login(String username,String password){
        log.info("用户名->[{}]",username);
        log.info("用户密码->[{}]",password);
        // 初始化返回给前端的携带状态码的map
        Map<String, Object> returnMap = new HashMap<>();
        try { // 认证成功
            User userDB = loginService.checkLogin(username, password);
            Map<String, String> payloadMap = new HashMap<>();
            payloadMap.put("uid",userDB.getUid().toString());
            payloadMap.put("username",userDB.getUsername());
            String token = JWTUtils.createToken(payloadMap); // 生成token
            returnMap.put("state",true);
            returnMap.put("msg","认证成功");
            returnMap.put("token",token);
        } catch (RuntimeException e) { // 认证失败
            returnMap.put("state",false);
            returnMap.put("msg",e.getMessage());
        }
        return returnMap;
    }

}
